package dnl.jexem.camouflaj;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;

public class LocalDirCommandManager extends DirBasedCommandManager{

	private File workDir;
	
	public LocalDirCommandManager(String workingDir){
		setWorkingDir(workingDir);
	}
	
	private File getWorkDirFile(){
		if(workDir == null){
			workDir = new File(getWorkingDir());
		}
		return workDir;
	}

	private File getFile(String fileName){
		return new File(getWorkDirFile(), fileName);
	}
	
	@Override
	protected void deleteFile(String fileName) throws IOException {
		FileUtils.forceDelete(new File(getWorkDirFile(), fileName));
	}

	@Override
	protected String readFileContentsImpl(String fileName) throws IOException {
		return FileUtils.readFileToString(getFile(fileName));
	}

	@Override
	protected Set<String> getFilesFromWorkDir(String fileNamePrefix) throws IOException {
		String[] list = getWorkDirFile().list(FileFilterUtils.prefixFileFilter(fileNamePrefix));
		return new HashSet<String>(Arrays.asList(list));
	}

	@Override
	protected Date getTimeStamp(String fileName) throws IOException {
		return new Date(getFile(fileName).lastModified());
	}

	@Override
	protected void saveFileImpl(String fileName, String content) throws IOException {
		FileUtils.writeStringToFile(getFile(fileName), content);
	}

	@Override
	protected boolean fileExists(String fileName) throws IOException {
		return getFile(fileName).exists();
	}

}
